package com.gitee.proxy.server;

import com.gitee.proxy.NettyHttpProxyApplication;
import com.gitee.proxy.handler.ServerInitalizer;
import com.gitee.proxy.util.LogUtil;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

public class HttpProxyServer {

    private ServerConfig serverConfig;

    /**
     * parent 线程组
     */
    private EventLoopGroup parent;

    /**
     * children 线程组
     */
    private EventLoopGroup children;

    private void init() {
        serverConfig = new ServerConfig();
        serverConfig.setProxyLoopGroup(new NioEventLoopGroup());
    }

    public void start(int port) {
        init();
        parent = new NioEventLoopGroup();
        children = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(parent, children)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.DEBUG))
                    .childHandler(new ServerInitalizer(serverConfig));
            ChannelFuture future = bootstrap.bind(port).sync();
            LogUtil.info(NettyHttpProxyApplication.class, "server start in {}", port);
            future.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            parent.shutdownGracefully();
            children.shutdownGracefully();
        }
    }
}
